import React from 'react';
import YAML from 'yaml';
// import md5 from 'md5';
import { message } from 'antd';
import Container from 'components/Container';
import Modal from 'components/ModalComponent';
import GraphTitle from './GraphTitle';
import PlayGraph from './PlayGraph';
import Drawer from './Drawer';
import { formatGraph, formatWorkFlow } from './format';

import AddDialog from '../AddDialog';

// import styles from './index.module.less';

const PlayDraw = ({
  playInfo,
  appList,
  scriptList,
  type,
  isCopy,
  disable,
  defaultTasks,
  addWorkFlows,
  editWorkFlows,
}) => {
  const [handleFunc, setHandleFunc] = React.useState({});
  const [visible, setVisible] = React.useState(false);
  const [dialogVisible, setDialogVisible] = React.useState(false);
  const [basicInfo, setBasicInfo] = React.useState();
  const [nodeInfo, setNodeInfo] = React.useState({});
  const [allEdges, setAllEdges] = React.useState([]);
  const [workFlow, setWorkFlow] = React.useState({
    tasks: [
      {
        loc: `${400} ${100}`,
        name: '流程开始',
        input: [],
        uuid: 'start',
      },
      {
        loc: `${400} ${400}`,
        name: '流程结束',
        // input,
        uuid: 'end',
      },
    ],
  });
  const [dragNode, setDragNode] = React.useState({});
  const handleSetNodeInfo = (param) => {
    setNodeInfo(param);
  };

  const handleSetEdges = (edges) => {
    setAllEdges(edges);
  };

  const setGraphAction = (func) => {
    setHandleFunc(func);
  };

  const handleDragNode = (node) => {
    setDragNode({ ...node._cfg.model });
  };

  const handleSave = () => {
    if (!basicInfo || !basicInfo.name) {
      message.error('请配置剧本名称');
      return;
    }
    const input = workFlow.input && workFlow.input.map(item => (item.id));
    const required = [];
    const properties = {};
    const schemas = {};
    if (workFlow.input) {
      workFlow.input.forEach((item) => {
        properties[item.id] = {
          name: item.name,
          type: item.type,
        };

        if (item.default) {
          properties[item.id].default = item.default;
        }

        if (item.required) {
          required.push(item.id);
        }
      });
    }
    schemas.properties = properties;
    schemas.required = required;
    const { tasks } = workFlow;
    const newTasks = {};
    if (!tasks) return;
    tasks.forEach((item) => {
      const task = item;
      // switch节点
      if (task.nodeType === 'switch') {
        task['on-success'] = {};
        const edges = allEdges.map(edge => item.uuid === edge.source && edge);
        if (edges) {
          edges.forEach((edge) => {
            // 左节点
            if (edge.sourceAnchor === 1) {
              task['on-success'].y = [{ [edge.target]: `<% task(${task.uuid}).result.content.condition = 'y' %>` }];
            }
            // 右节点
            if (edge.sourceAnchor === 2) {
              task['on-success'].n = [{ [edge.target]: `<% task(${task.uuid}).result.content.condition = 'n' %>` }];
            }
          });
        }
      } else {
        // 常规节点
        const edges = allEdges.find(edge => item.uuid === edge.source);
        if (edges) {
          // if (task['on-success']) {
          //   task['on-success'].default = [...task['on-success'].default, edges.target];
          // } else {
          task['on-success'] = { default: [edges.target] };
          // }

          if (task.errorStop) {
            // if (task['on-error']) {
            //   task['on-error'].default = [...task['on-error'].default, edges.target];
            // } else {
            task['on-error'] = { default: [edges.target] };
            // }
          }
        }
      }

      // 处理3种节点 action
      if (task.uuid === 'start') {
        task.action = 'start using="" intergration=false';
      } else if (task.uuid === 'end') {
        task.action = 'end using="" intergration=false';
      } else {
        const NodeInput = task.input && Object.keys(task.input).map(param => (`${param}=<% $.${task.input[param] || ''} %>`));
        task.action = `${task.actionName} ${NodeInput.join(' ')} app="${task.app || ''}" script="${task.script || ''}" isSwitch=${task.isSwitch || false} using="${task.using || ''}" integration=${task.integration || false}`;
      }

      // 处理4种节点 publish
      if (task.uuid === 'start') {
        task.publish = { data: `<% task(${task.uuid}).result.content.data %>` };
      } else if (task.uuid === 'end') {
        task.publish = { data: `<% task(${task.uuid}).result.content.data %>` };
      } else if (task.nodeType === 'switch') {
        task.publish = { condition: `<% task(${task.uuid}).result.content.condition %>` };
      } else {
        const output = {};
        if (task.output) {
          Object.keys(task.output).forEach((param) => {
            output[param] = `<% task(${task.uuid}).result.content.${task.output[param]} %>`;
          });
        }
        // const output = task.output && Object.keys(task.output).map(param =>
        // ({ [param]: `<% task(${task.uuid}).result.content.${task.output[param]}` }));
        task.publish = output;
      }
      // return task;
      newTasks[task.uuid] = {
        action: task.action,
        loc: task.loc,
        // eslint-disable-next-line no-nested-ternary
        nick: task.uuid === 'start' ? '流程开始' : task.uuid === 'end' ? '流程结束' : task.nick,
        // 'on-success': task['on-success'],
        publish: task.publish,
      };
      if (task.description !== undefined) {
        newTasks[task.uuid].description = task.description;
      }
      if (task.uuid !== 'end') {
        newTasks[task.uuid]['on-success'] = task['on-success'];
      }
    });
    const newWorkFlow = {
      // created_at: new Date(),
      // version: '2.0',
      // definition: '',
      // name: basicInfo.name,
      description: basicInfo.description,
      // namespace: '',
      input: input || [],
      schemas,
      tasks: newTasks,
      runner: 'workflow',
      type: 'direct',
      // tags: basicInfo.tags || [],
      // is_system: false,
      // project_id: null,
      // run_last_at: null,
      // scope: 'private',
    };
    if (basicInfo.tags) {
      newWorkFlow.tags = basicInfo.tags;
    }
    const definition = {};
    definition[basicInfo.name] = newWorkFlow;
    definition.version = '2.0';
    // const newPlayBook = {
    //   // created_at: new Date(),
    //   // version: '2.0',
    //   definition: YAML.stringify(newWorkFlow),
    //   name: basicInfo.name,
    //   description: basicInfo.description,
    //   namespace: '',
    //   input,
    //   schemas,
    //   // tasks: newTasks,
    //   tags: basicInfo.tags,
    //   is_system: false,
    //   project_id: null,
    //   run_last_at: null,
    //   scope: 'private',
    // };

    // console.log(definition, YAML.stringify(definition));
    // addWorkFlows({
    //   // id: md5(new Date().getTime()),
    //   // namespace: 'wl',
    //   workflow: YAML.stringify(definition),
    // });
    if (type === 'editPlay' && !isCopy) {
      editWorkFlows({ id: playInfo.id, definition: YAML.stringify(definition) });
    } else {
      addWorkFlows(YAML.stringify(definition));
    }
  };

  React.useEffect(() => {
    setVisible(false);
    if (playInfo && type === 'editPlay') {
      const { name, description, tags } = playInfo;
      if (tags && tags.length) {
        setBasicInfo({ name: isCopy ? `${name}_copy` : name, description, tags });
      } else {
        setBasicInfo({ name: isCopy ? `${name}_copy` : name, description });
      }
      setWorkFlow({ ...workFlow, ...formatWorkFlow(playInfo) });
    }
  }, [playInfo]);

  React.useEffect(() => {
    if (type === 'addPlay') {
      setDialogVisible(true);
    }
  }, [type]);

  React.useEffect(() => {
    if (dragNode.id && workFlow.tasks) {
      const tasks = workFlow.tasks.map((item) => {
        if (item.uuid === dragNode.id) {
          return { ...item, loc: `${dragNode.x} ${dragNode.y}` };
        }
        return item;
      });
      setWorkFlow({ ...workFlow, tasks });
    }
  }, [dragNode]);

  return (
    <Container>
      <GraphTitle
        handleFunc={handleFunc}
        type={disable ? 'view' : 'edit'}
        setVisible={setDialogVisible}
        handleSave={handleSave}
      />
      <PlayGraph
        task={playInfo ? formatGraph(playInfo) : defaultTasks}
        id={playInfo && playInfo.id}
        disable={disable}
        // workFlow={workFlow}
        setGraphAction={setGraphAction}
        setVisible={setVisible}
        setNodeInfo={handleSetNodeInfo}
        setEdgesInfo={handleSetEdges}
        handleDragNode={handleDragNode}
      />
      <Drawer
        visible={visible}
        appList={appList}
        type={disable ? 'view' : 'edit'}
        nodeInfo={nodeInfo}
        scriptList={scriptList}
        workFlow={workFlow}
        setWorkFlow={setWorkFlow}
        setVisible={setVisible}
      />
      <Modal
        title={type === 'addPlay' ? '新增剧本' : '编辑剧本'}
        visible={dialogVisible}
        onCancel={() => { setDialogVisible(false); }}
      >
        <AddDialog
          visible={dialogVisible}
          basicInfo={basicInfo}
          setVisible={setDialogVisible}
          setBasicInfo={setBasicInfo}
        />
      </Modal>
    </Container>
  );
};

export default PlayDraw;
